package core.servlets;

import static core.util.StoredData.storedSessionData;
import static core.util.Utilities.COOKIE_NAME;
import static core.util.Utilities.redirectPage;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import core.util.MyCookieValue;

public class LogoutServlet extends HttpServlet {
	/**
     * 
     */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Cookie[] cookies = request.getCookies();
		MyCookieValue cookieValue = null;
		// get our cookie
		Cookie cookie = null;
		if (cookies != null) {
			for (Cookie c : cookies) {
				cookie = c;
				if (COOKIE_NAME.equalsIgnoreCase(cookie.getName())) {
					cookie.setMaxAge(0); // this should cause the browser to
											// delete the cookie
					cookieValue = MyCookieValue.buildFromString(cookie
							.getValue());
					break;
				}
			}
		}

		// if no cookie is found, there is nothing to delete
		if (cookieValue != null) {
			String sessionId = cookieValue.getSessionId();
			storedSessionData.remove(sessionId);
		}

		response.addCookie(cookie);

		redirectPage(response, "bye.html");
	}
}
